<template>
  <view class="notice-container" >
    <view ref="noticeTopBox" class="notice-top-box" :style="{ padding: `0 ${padding}px 20px ${padding}px` }">
      <view class="notice-title">{{ notice.title }}</view>
      <view class="notice-code">{{ notice.code }}</view>
      <view class="notice-line"></view>
      <view class="notice-main-title">{{ notice.mainTitle }}</view>
      <view class="notice-info-row">
        <text class="notice-info-left">{{ notice.leftText }}</text>
      </view>
      <view class="notice-info-right">
        <text class="notice-author">{{ notice.author }}</text>
        <text class="notice-date">{{ notice.date }}</text>
      </view>
      <view class="notice-line light"></view>
      <view class="notice-copy">{{ notice.copy }}</view>
      <view class="notice-read">{{ notice.read ||1 }}</view>
    </view>
    <view  :style="{ padding: `0 ${padding}px 20px ${padding}px`,background:'#fff' }" >
      <view class="notice-content">
        <view class="notice-content-title">附件材料</view>
        <!-- 附件列表 -->
        <view v-if="attachmentList && attachmentList.length > 0" class="attachment-list">
          <view 
            v-for="(attachment, index) in attachmentList" 
            :key="index"
            class="attachment-item"
            @click="handleAttachmentClick(attachment)"
          >
            <u-icon name="file-text" size="16" color="#3B75FA"></u-icon>
            <text class="attachment-name">{{ attachment.displayName }}</text>
            <u-icon name="arrow-right" size="14" color="#999"></u-icon>
          </view>
        </view>
        
        <view v-else class="no-attachment">
          暂无附件
        </view>
      </view>
    </view>
    <!-- 新增底部按钮区 -->
     <view class="u-p-b-20">
    <view class="notice-bottom-btns "  >
     
      <view class="save-btn" @click="handleSave">
        <u-icon name="download" size="20" color="#0030a7"></u-icon>
        <text>保存为图片</text>
      </view>
       <button class="share-box share-btn" open-type="share">
         分享给邻居
      </button>
      </view>
    
    </view>
    <!-- 隐藏canvas，仅用于保存图片 -->
    <canvas
      canvas-id="noticeCanvas"
      id="noticeCanvas"
      :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px', position: 'absolute', left: '-9999px', top: '-9999px' }"
    ></canvas>
  </view>
</template>

<script>
import {getNoticeDetail,createWxacode,getReadNum,updateReadNum} from '@/api/index'
import {mapState,mapMutations} from 'vuex'
import {name} from "@/util/config"
import {handleFile,parseAttachmentList,parseSceneParams} from "@/util/function"
export default {
  data() {
    return {
      id:0,
      canvasWidth: 375,
      canvasHeight: 700, // 初始默认值，后续动态赋值
      padding: 12, // px，和页面padding一致
      notice: {
        title: '',
        code: '',
        mainTitle: '',
        leftText: ``,
        author: '',
        date: '',
        copy: '',
        read: '',
        bottomMain: `本公告由 ${name} 小程序创建`,
        bottomSub: '基于区块链、云服务技术助力业主就小区公共事务达成共识',
        qr: 'https://ainij.oss-cn-beijing.aliyuncs.com/pms/20250711/1214695284041052160.png'
      },
      bottomBoxTopPadding: 30, // 顶部内边距
      bottomBoxBottomPadding: 12, // 底部内边距
      qrLocalPath: '', // 本地二维码图片路径
      attachmentList:[],
      marginBo:false
    }
  },
  computed:{
    ...mapState('app',['safeAreaInsetsBottom']),
    ...mapState('community',['communityId'])
  },
 onShareAppMessage(res) {
    return {
      title:this.notice.title,
      path: `/pages/notice/index?id=${this.id}&communityId=${this.communityId}`
    }
  },
  onLoad(options) {
    this.init(options)
    // 这里可以添加初始化逻辑
  },
  onReady() {
    // 页面渲染后自动计算高度
    // this.calcCanvasHeight();
  },
  methods: {
  ...mapMutations('community',['setCommunityId']),

  
  

  

 async createCode(){
   
  let data=await  createWxacode({
      pageUrl:'pages/notice/index',
      picSize:430,
      scene:`communityId=${this.communityId}&id=${this.id}`
    })
    
      if (data && data.url) {
        this.notice.qr = data.url;
        // 下载二维码图片到本地
        // this.downloadQrImage(data.url);
      }
    },
    async getList(id){
      let data1=await getReadNum({id:id})
     
 
       let res = await getNoticeDetail({
          id: id
        })

        if (res.code === 200 && res.data) {
          let row = res.data;
          let readNum=data1.data+1
          // 确保数据有效，提供默认值
          this.notice.title=row.noticeType
      
          this.notice.leftText =row.content
          this.notice.mainTitle = row.noticeTitle || '标题';
          this.notice.author = row.initiator || '';
          this.notice.date = row.noticeDate || '';
          this.notice.copy = `抄送：${row.sender}` || '';
          this.notice.read = `阅读${readNum}` || "阅读1";
          updateReadNum({id:id,readNum:readNum})
          
          // 处理附件列表
          this.attachmentList = parseAttachmentList(row.fileUrl)
        } else {
          console.error("接口返回数据异常:", res);
        }
    },
    async init(options){
      if(options.scene){
        options=parseSceneParams(options)
      }
      try {
        this.id = options.id
        this.setParams(options)
        this.getList(this.id)
        this.createCode()
      } catch (error) {
        console.error("获取公告详情失败:", error);
      }
    
    },
    setParams(options){
       if(options.communityId){
     
        this.setCommunityId(options.communityId)
       }
    },
   
    // 下载二维码图片到本地
    downloadQrImage(imageUrl) {
     return new Promise((resolve,reject)=>{
      uni.downloadFile({
        url: imageUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            this.qrLocalPath = res.tempFilePath;
         
            resolve(res)
          } else {
            console.error('二维码图片下载失败:', res.errMsg);
          }
        },
        fail: (error) => {
          console.error('二维码图片下载失败:',  error.errMsg);
          reject(error)
        }
      });
     })
    },
    drawTextAutoLine(ctx, text, x, y, maxWidth, lineHeight) {
      // 检查text是否为有效字符串
      if (!text || typeof text !== 'string') {
  
        return;
      }
      
      let line = '';
      let testLine = '';
      let lineArr = [];
      for (let i = 0; i < text.length; i++) {
        testLine = line + text[i];
        let metrics = ctx.measureText(testLine);
        if (metrics.width > maxWidth && i > 0) {
          lineArr.push(line);
          line = text[i];
        } else {
          line = testLine;
        }
      }
      lineArr.push(line);
      for (let j = 0; j < lineArr.length; j++) {
        ctx.fillText(lineArr[j], x, y + j * lineHeight);
      }
    },
    getTextLines(ctx, text, maxWidth) {
      // 检查text是否为有效字符串
      if (!text || typeof text !== 'string') {
     
        return 0;
      }
      
      
      let line = '';
      let testLine = '';
      let lineArr = [];
      for (let i = 0; i < text.length; i++) {
        testLine = line + text[i];
        let metrics = ctx.measureText(testLine);
        if (metrics.width > maxWidth && i > 0) {
          lineArr.push(line);
          line = text[i];
        } else {
          line = testLine;
        }
      }
      
      lineArr.push(line);
     
      return lineArr.length;
    },
    // 计算底部说明区域高度
    calcBottomBoxHeight(ctx) {
      const bottomWidth = 240;
      const qrSize = 80;
      const mainText = this.notice.bottomMain;
      const mainLineHeight = 22;
      ctx.font = '12px sans-serif'; // bottomMain
   
      const mainLines = this.getTextLines(ctx, mainText, bottomWidth);
      const subText = this.notice.bottomSub;
      const subLineHeight = 20;
      ctx.font = '10px sans-serif'; // bottomSub
      
      const subLines = this.getTextLines(ctx, subText, bottomWidth);
     
      const textHeight = mainLines * mainLineHeight + 4 + subLines * subLineHeight;
      const bottomBoxHeight = Math.max(
        textHeight + this.bottomBoxTopPadding + this.bottomBoxBottomPadding,
        qrSize
      );
      return bottomBoxHeight;
    },
    // 动态计算canvas高度
    calcCanvasHeight() {
      // 1. 先获取notice-top-box实际高度
      this.$nextTick(() => {
        uni.createSelectorQuery().in(this).select('.notice-top-box').boundingClientRect(rect => {
          const topBoxHeight = rect ? rect.height : 0;
          // 2. 用canvas上下文计算底部说明区域高度
          const ctx = uni.createCanvasContext('noticeCanvas', this);
          const bottomBoxHeight = this.calcBottomBoxHeight(ctx);

           let topBoxHeights=topBoxHeight*1.2

          // 3. 计算总高度（加一点安全间距）

          this.canvasHeight = (Math.ceil(topBoxHeights + 28 + bottomBoxHeight + 24)+50); // 28为"阅读-底部说明"间距，24为底部安全边距
       
       }).exec();
      });
    },
    async handleSave() {
      // 检查二维码图片是否已下载
      if (!this.qrLocalPath) {
        await this.downloadQrImage(this.notice.qr)
        // uni.showToast({ 
        //   title: '二维码图片正在加载中，请稍后再试', 
        //   icon: 'none' 
        // });
        // return;
      }
      
      // 先动态计算高度再绘制
      this.calcCanvasHeight();
      setTimeout(() => {
        this.saveCanvasImage();
      }, 100); // 等待高度更新
    },
    handleShare() {
      // 你的分享逻辑
      uni.showToast({ title: '分享功能待实现', icon: 'none' });
    },
    saveCanvasImage() {
      uni.showLoading({
        title: '保存中...',
        mask: true
      });
      const ctx = uni.createCanvasContext('noticeCanvas', this);
      ctx.setFillStyle('#fff');
      ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
      const padding = this.padding;
      const contentWidth = this.canvasWidth - padding * 2;
      const bottomWidth = 240;
      // ===== 绘制上半部分内容（与页面一致） =====
      let y = 50;
      ctx.setFillStyle('#E25A2B');
      ctx.setFontSize(28);
      ctx.setTextAlign('center');
      ctx.fillText(this.notice.title, this.canvasWidth / 2, y);
      y += 40;
      ctx.setFontSize(18);
      ctx.fillText(this.notice.code, this.canvasWidth / 2, y);
      y += 20;
      ctx.setStrokeStyle('#E25A2B');
      ctx.setLineWidth(2);
      ctx.beginPath();
      ctx.moveTo(padding, y);
      ctx.lineTo(this.canvasWidth - padding, y);
      ctx.stroke();
      y += 40;
      ctx.setFillStyle('#222');
      ctx.setTextAlign('center');
      ctx.font = 'bold 20px sans-serif';
      ctx.fillText(this.notice.mainTitle, this.canvasWidth / 2, y);
      y += 40;
      ctx.setFillStyle('#333');
      ctx.setFontSize(16);
      ctx.setTextAlign('left');
      ctx.font = '14px sans-serif'; // 去掉加粗，使用普通字体
      const leftText = this.notice.leftText;
      const leftLineHeight = 22;
      const leftMaxWidth = contentWidth;
      const leftLines = this.getTextLines(ctx, leftText, leftMaxWidth);
      this.drawTextAutoLine(ctx, leftText, padding, y, leftMaxWidth, leftLineHeight);
      y += leftLines * leftLineHeight + 16;
      ctx.setTextAlign('right');
      ctx.font = 'bold 16px sans-serif';
      ctx.fillText(this.notice.author, this.canvasWidth - padding, y);
      ctx.font = '14px sans-serif';
      ctx.fillText(this.notice.date, this.canvasWidth - padding, y + 25);
      y += 50;
      ctx.setStrokeStyle('#ccc');
      ctx.setLineWidth(1);
      ctx.beginPath();
      ctx.moveTo(padding, y);
      ctx.lineTo(this.canvasWidth - padding, y);
      ctx.stroke();
      y += 40;
      ctx.setFillStyle('#888');
      ctx.setFontSize(16);
      ctx.setTextAlign('left');
      ctx.fillText(this.notice.copy, padding, y);
      y += 28; // 抄送和阅读间距
      ctx.setFontSize(12);
      ctx.setFillStyle('#bbb');
      ctx.font = '12px sans-serif';
      ctx.fillText(this.notice.read, padding, y);
      // ===== 绘制底部说明区域（贴合计算好的canvas底部） =====
      const qrSize = 80;
      const mainText = this.notice.bottomMain;
      const mainLineHeight = 22;
      ctx.font = '12px sans-serif'; // bottomMain
      const mainLines = this.getTextLines(ctx, mainText, bottomWidth);
      const subText = this.notice.bottomSub;
      const subLineHeight = 20;
      ctx.font = '10px sans-serif'; // bottomSub
      const subLines = this.getTextLines(ctx, subText, bottomWidth);
      const bottomBoxPadding = 12;
      const textHeight = mainLines * mainLineHeight + 4 + subLines * subLineHeight;
      const bottomBoxHeight = Math.max(
        textHeight + this.bottomBoxTopPadding + this.bottomBoxBottomPadding,
        qrSize
      );
      // 让底部区域从canvas底部开始，向上绘制
      const bottomBoxY = this.canvasHeight - bottomBoxHeight;
      const textY = bottomBoxY + this.bottomBoxTopPadding;
      const bottomBoxBgColor = '#f5f7fa';
      const bottomBoxX = padding - bottomBoxPadding;
      const bottomBoxW = this.canvasWidth - 2 * (padding - bottomBoxPadding);
      const bottomBoxH = bottomBoxHeight;
      const bottomBoxRadius = 12;
      ctx.setFillStyle(bottomBoxBgColor);
      ctx.beginPath();
      ctx.moveTo(bottomBoxX + bottomBoxRadius, bottomBoxY);
      ctx.lineTo(bottomBoxX + bottomBoxW - bottomBoxRadius, bottomBoxY);
      ctx.quadraticCurveTo(bottomBoxX + bottomBoxW, bottomBoxY, bottomBoxX + bottomBoxW, bottomBoxY + bottomBoxRadius);
      ctx.lineTo(bottomBoxX + bottomBoxW, bottomBoxY + bottomBoxH - bottomBoxRadius);
      ctx.quadraticCurveTo(bottomBoxX + bottomBoxW, bottomBoxY + bottomBoxH, bottomBoxX + bottomBoxW - bottomBoxRadius, bottomBoxY + bottomBoxH);
      ctx.lineTo(bottomBoxX + bottomBoxRadius, bottomBoxY + bottomBoxH);
      ctx.quadraticCurveTo(bottomBoxX, bottomBoxY + bottomBoxH, bottomBoxX, bottomBoxY + bottomBoxH - bottomBoxRadius);
      ctx.lineTo(bottomBoxX, bottomBoxY + bottomBoxRadius);
      ctx.quadraticCurveTo(bottomBoxX, bottomBoxY, bottomBoxX + bottomBoxRadius, bottomBoxY);
      ctx.closePath();
      ctx.fill();
      // 主说明
      let mainTextY=textY+5
      ctx.font = '12px sans-serif'; // bottomMain
      ctx.setFillStyle('#333');
      this.drawTextAutoLine(ctx, mainText, padding + bottomBoxPadding, mainTextY, bottomWidth, mainLineHeight);
      // 副说明
      ctx.font = '11px sans-serif'; // bottomSub
      ctx.setFillStyle('#888');
      const subTextY = textY + mainLines * mainLineHeight + 4;
      this.drawTextAutoLine(ctx, subText, padding + bottomBoxPadding, subTextY, bottomWidth, subLineHeight);
      // 二维码
      const qrY = textY - 15;
      const qrX=this.canvasWidth - padding - qrSize - bottomBoxPadding+10
      if (this.qrLocalPath) {
        ctx.drawImage(this.qrLocalPath,qrX , qrY, qrSize, qrSize);
      } else {
       
      }
      ctx.draw(false, () => {
        uni.canvasToTempFilePath({
          canvasId: 'noticeCanvas',
          success: res => {
            uni.hideLoading();
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                uni.showToast({ title: '保存成功', icon: 'success' });
              },
              fail: () => {
                // uni.showToast({ title: '保存失败', icon: 'none' });
              }
            });
          },
          fail: () => {
              uni.hideLoading();
            // uni.showToast({ title: '生成图片失败', icon: 'none' });
          }
        }, this);
      });
    },
    // 处理附件点击
    handleAttachmentClick(attachment) {
      // 使用公共文件处理函数
      handleFile(attachment.realUrl, attachment.displayName)
        .then(() => {
          
        })
        .catch((error) => {
          console.error('文件处理失败:', error)
        })
    },
    // 下载文件
    async downloadFile(url, fileName) {
      uni.showLoading({
        title: '下载中...',
        mask: true
      })
      
      try {
        const res = await this.downloadQrImage(url)
        if (res && res.tempFilePath) {
          // 保存文件到本地
          uni.saveFile({
            tempFilePath: res.tempFilePath,
            success: (saveRes) => {
              uni.hideLoading()
              uni.showToast({
                title: '文件保存成功',
                icon: 'success'
              })
            
            },
            fail: (error) => {
              uni.hideLoading()
              uni.showToast({
                title: '文件保存失败',
                icon: 'none'
              })
              console.error('文件保存失败:', error)
            }
          })
        } else {
          uni.hideLoading()
          uni.showToast({
            title: '文件下载失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '文件下载失败',
          icon: 'none'
        })
        console.error('文件下载失败:', error)
      }
    }
  }
}
</script>

<style scoped lang="scss" >
.notice-top-box{
  background: #fff;


}
.notice-container {
  background: $uni-bg-color-grey;
  width: 100vw;
  min-height: 100vh;
  box-sizing: border-box;
 
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  position: relative;
}
.notice-title {
  color: #E25A2B;
  font-size: 44rpx;
  font-weight: bold;
  text-align: center;
  margin-top: 60rpx;
}
.notice-code {
  color: #E25A2B;
  font-size: 28rpx;
  text-align: center;
  margin-top: 16rpx;
}
.notice-line {
  height: 2rpx;
  background: #E25A2B;
  margin: 24rpx 0 0 0;
  width: 100%;
}
.notice-line.light {
  background: #ccc;
  margin: 40rpx 0 0 0;
}
.notice-main-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #222;
  text-align: center;
  margin: 40rpx 0 32rpx 0;
}
.notice-info-row {
  margin-bottom: 0;
}
.notice-info-left {
  font-size: 28rpx;
  color: #333;
   word-break: break-all;    
  white-space: pre-line;     
}
.notice-info-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  margin-bottom: 16rpx;
}
.notice-author {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}
.notice-date {
  font-size: 24rpx;
  color: #333;
  margin-top: 4rpx;
}
.notice-copy {
  color: #888;
  font-size: 28rpx;
  margin: 40rpx 0 0 0;
}
.notice-read {
  color: #bbb;
  font-size: 24rpx;
  margin: 32rpx 0 0 0;
}
.save-btn {
 
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #333;
  font-size: 26rpx;
  border-radius: 12rpx;
}
.notice-bottom-btns {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100vw;
  background: #fff;
  padding: 16rpx 24rpx 32rpx 24rpx;
  box-sizing: border-box;
  z-index: 10;
}

.btn-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}
.share-btn {
  flex: 1;
  margin-left: 24rpx;
  background: $uni-color-primary !important;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 32rpx;
  border-radius: 12rpx;
  height: 80rpx;
  border: none;
}
.attachment-list {
  margin-top: 20rpx;
  padding: 10rpx 0;

}
.attachment-item {
  display: flex;
  align-items: center;
  padding: 10rpx 0;
  cursor: pointer;
}
.attachment-name {
  flex: 1;
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.no-attachment {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  font-size: 28rpx;
}
</style>